from functools import lru_cache
from typing import Optional
from pydantic_settings import BaseSettings
import os
from pathlib import Path

class Settings(BaseSettings):
    """应用配置管理类"""
    
    # 数据库配置
    DB_USER: str
    DB_PASSWORD: str
    DB_HOST: str
    DB_PORT: int
    DB_NAME: str

    # 应用配置
    ENV: str = "development"
    DEBUG: bool = True
    API_V1_PREFIX: str
    HOST: str
    PORT: int
    RELOAD: bool
    
    # 日志配置
    LOG_FILE: str
    LOG_LEVEL: int
    LOG_BACKUP_COUNT: int
    LOG_TO_CONSOLE: bool
    
    # 安全配置
    SECRET_KEY: str

    @property
    def DATABASE_URL(self) -> str:
        """构建MySQL数据库连接URL (Tortoise ORM格式)"""
        return (
            f"mysql://{self.DB_USER}:{self.DB_PASSWORD}@"
            f"{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
        )

    @property
    def PROJECT_ROOT(self) -> Path:
        """获取项目根目录"""
        return Path(__file__).parent.parent

    @property
    def LOG_PATH(self) -> Path:
        """获取日志文件完整路径"""
        log_path = Path(self.LOG_FILE)
        if not log_path.is_absolute():
            log_path = self.PROJECT_ROOT / self.LOG_FILE
        return log_path

    class Config:
        env_file = ".env"
        case_sensitive = True

@lru_cache()
def get_settings() -> Settings:
    """
    获取应用配置单例
    Returns:
        Settings: 配置对象实例
    """
    return Settings()

# 导出配置单例
settings = get_settings()